
<template>
  <el-container  v-loading="loading"
   v-loading.fullscreen.lock="fullscreenLoading"
    :element-loading-text="$t('message.rebooting')">
    <el-aside width="19%">
      <el-row class="tac">
        <el-col :span="24" class="col24">
          <div class="product">
            <p >{{system.productInfo.modelNameId}}</p>
          </div>
          <el-menu class="menu"  background-color="#324057" text-color="#bfcbd9" :default-active="$route.matched[1].path" router>
            <router-link v-for="router in routers" :key="router.path" :to='router.path' >	
              <el-menu-item :index="router.path">
                <span slot="title" >{{$t(router.name)}}	</span><i :class="router.icon"></i>         
              </el-menu-item>
            </router-link> 
          </el-menu>
        	<el-row class="sidefoot">
						<el-col :span="10">
						<img :src="src" alt="" style="width:65px;height:50px;margin-left:10px;margin-bottom:10px;">
						</el-col >
						<el-col :span="14" style="margin-top:10px;">
              <a :href="system.companyInfo.site" target="_blank" style="color:inherit;font-size:14px;" >{{system.companyInfo.site}}</a>
						</el-col>					
					</el-row>	
        </el-col>
      </el-row>
    </el-aside>
    <el-container>
      <el-header>
        <el-row class="height100">
          <el-col :span="23" style="margin-top:20px;">
      <el-breadcrumb class="app-levelbar" separator=">">
        <el-breadcrumb-item v-for="(item,index)  in levelList" :key="item.path">
          <router-link v-if='item.redirect==="noredirect"||index==levelList.length-1' :to="item.path" class="no-redirect">{{$t('message.'+item.name)}}</router-link>
          <router-link v-else :to="item.redirect||item.path">{{system.isSpecialType && item.name == "streampull" ? $t('message.medias.netstreampull') : $t('message.'+item.name)}}</router-link>
        </el-breadcrumb-item>
      </el-breadcrumb>
          </el-col>
          <el-col :span="1">
            <el-dropdown class="dropdown" trigger="click" placement="bottom"  @command="handleCommand" style="cursor:pointer">
              <img src="../../../assets/img/avator.jpg" class="avator">
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item v-for="item in sysCmds" :key="item.name" :command="item.command">{{item.name}}</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </el-col>
        </el-row>
      </el-header>
      <el-main>
        <router-view></router-view>
      </el-main>
    </el-container>
    <!-- 修改密码弹窗框 -->
    <el-dialog :visible.sync="dialogVisible" width="25%">
     <el-form ref="authInfo" :model="authInfo" :rules="rules" label-width="80px">
      <el-form-item :label="$t('message.username')" prop="username">
        <el-input v-model="authInfo.username"></el-input>
      </el-form-item>
      <el-form-item :label="$t('message.oldpassword')" prop="oldpassword">
        <el-input type="password" v-model="authInfo.oldpassword"></el-input>
      </el-form-item>
      <el-form-item :label="$t('message.newpassword')" prop="newpassword">
        <el-input type="password" v-model="authInfo.newpassword"></el-input>
      </el-form-item>
      <el-form-item :label="$t('message.confirmpassword')" prop="confirmpassword">
        <el-input type="password" v-model="authInfo.confirmpassword" name="confirmpassword"></el-input>
        <span v-show="equalPwd" class="text-style" > {{ errors.first('confirmpassword') }} </span>  
      </el-form-item>
      <el-button type="primary" @click="onSubmit" style="margin-left:37%">{{$t('message.ok')}}</el-button>
      <el-button @click="dialogVisible = false">{{$t('message.cancel')}}</el-button>
    </el-form>     
</el-dialog>
  </el-container>
</template>

<script>
import { mapState } from "vuex";
import { getHostName, api } from "../../../libs/api";
import ebus from "../../../libs/ebus.js";
import md5 from "js-md5";
import axios from "axios";
import * as zh from '../../../locales/cn.js'
import * as en from '../../../locales/en.js'
import locale from 'element-ui/lib/locale'
import enLocale from 'element-ui/lib/locale/lang/en'
import zhLocale from 'element-ui/lib/locale/lang/zh-CN'
import { downloadFile } from '@/libs/utils'

export default {
  created() {
    ebus.emit("getInputChannelInfo", this);
    ebus.emit("getInputDevInfo", this);
    ebus.emit("getOutputChannelInfo", this);
    ebus.emit("getOutputDevInfo", this);
    ebus.emit("getMulticaseInfo", this);
    
   this.getCustomInfo();                  //加载公司名称、网站地址等信息
   this.getServerI18nlocales('zh-cn');    //加载中文翻译资源
   this.getServerI18nlocales('en');       //加载英文翻译资源
  },
  computed: {
    ...mapState(["system"]), 
    ...mapState(["kvm"]), 
    levelList() {
      let matched = this.$route.matched.filter(item => item.name);
      return matched;
    },
    equalPwd() {
      return this.newpassword !== this.confirmpassword;
    },
    src() {
      var src = "http://" + getHostName() + ":8080/custom/logo.png";
      if (
        this.system &&
        this.system.companyInfo &&
        this.system.companyInfo.logo
      ) {
        src =
          "http://" + getHostName() + ":8080/" + this.system.companyInfo.logo;
      }
      return src;
    },
    sysCmds() {
      return [
        {
          command: "translate",
          name: this.$t("message.systems.translate")
        },
        {
          command: "logout",
          name: this.$t("message.systems.logout")
        },
        {
          command: "changpsw",
          name: this.$t("message.systems.changpsw")
        },
        {
          command: "shutdown",
          name: this.$t("message.systems.shutdown")
        },
        {
          command: "reboot",
          name: this.$t("message.systems.reboot")
        },
        {
          command: "clearusersetting",
          name: this.$t("message.systems.clearusersetting")
        },
        {
          command: "factory",
          name: this.$t("message.systems.factory")
        },
        {
          command: "exportlog",
          name: this.$t("message.systems.exportlog")
        },
        // {
        //   command: "tool",
        //   name: this.$t("message.systems.tool")
        // }
      ];
    },
    routers(){
      var routers = [];
       routers =[
        {
          path: '/system',
          name: 'message.system',
          icon: 'iconfont el-icon-erp-xitongshezhi'
        },
        {
          path: '/media',
          name: 'message.media',
          icon: 'iconfont el-icon-erp-meiti'
        },
        {
          path: '/debug',
          name: 'message.debug',
          icon: 'iconfont el-icon-erp-xitongweihu'
        },
      ]
      if(!this.kvm.hideComSetting || !this.kvm.hideIrOutSetting || !this.kvm.hideKvm ){
        routers.splice(2, 0, {
          path: '/kvm',
          name: 'message.kvm',
          icon: 'iconfont el-icon-erp-kongzhizhongxin'
        });//隐藏中控管理
      }
      return routers;
    }
  },
  data() {
    var checkConfirPwd = (rule, value, callback) => {
      if (this.authInfo.newpassword != this.authInfo.confirmpassword) {
        return callback(new Error(this.$t("message.systems.checkConfirmPwd")));
      }
    };
    return {
      routers1:[
        {
          path: '/system',
          name: 'message.system',
          icon: 'iconfont el-icon-erp-xitongshezhi'
        },
        {
          path: '/media',
          name: 'message.media',
          icon: 'iconfont el-icon-erp-meiti'
        },
        {
          path: '/kvm',
          name: 'message.kvm',
          icon: 'iconfont el-icon-erp-kongzhizhongxin'
        },
        {
          path: '/debug',
          name: 'message.debug',
          icon: 'iconfont el-icon-erp-xitongweihu'
        },
      ],
      rules: {
        username: [
          {
            required: true,
            message: this.$t("message.systems.requireUserName")
          }
        ],
        oldpassword: [
          { required: true, message: this.$t("message.systems.requireOldePwd") }
        ],
        newpassword: [
          { required: true, message: this.$t("message.systems.requireNewPwd") }
        ],
        confirmpassword: [
          {
            required: true,
            message: this.$t("message.systems.requireConfirmPwd")
          },
          { validator: checkConfirPwd }
        ]
      },
      authInfo: {
        username: "",
        oldpassword: "",
        newpassword: "",
        confirmpassword: ""
      },
      dialogVisible: false,
      loading: false, 
      fullscreenLoading: false,   

    };
  },
  methods: {
    handleCommand(command) {
      if (command == "translate") {
        if (this.$i18n.locale == "zh-cn") {
          this.$i18n.locale = "en";
          locale.use(enLocale);
          ebus.emit("onChangeLang", "en");
          return;
        } else {
          this.$i18n.locale = "zh-cn";
          locale.use(zhLocale);
          ebus.emit("onChangeLang", "cn");
          return;
        }
      } else if (command == "logout") {
        ebus.emit("disconnct");
        api.DisConnect()
        this.$router.push("/login");
      } else if (command == "changpsw") {
        this.authInfo.username = this.system.auth.username;
        this.dialogVisible = true;
      } else if (command == "shutdown") {
        this.$confirm(this.$t("message.areyousure"), this.$t("message.ok"), {
          confirmButtonText: this.$t("message.ok"),
          cancelButtonText: this.$t("message.cancel"),
          type: "warning"
        }).then(() => {
          this.doSendCmd("shutdown");
        });
      } else if (command == "reboot") {
        this.$confirm(this.$t("message.areyousure"), this.$t("message.ok"), {
          confirmButtonText: this.$t("message.ok"),
          cancelButtonText: this.$t("message.cancel"),
          type: "warning"
        }).then(() => {
          this.onReboot();
        });
      } else if (command == "clearusersetting") {
        this.$confirm(this.$t("message.areyousure"), this.$t("message.ok"), {
          confirmButtonText: this.$t("message.ok"),
          cancelButtonText: this.$t("message.cancel"),
          type: "warning"
        }).then(() => {
          this.doSendCmd("clearUsrSettings");
        });
      } else if (command == "factory") {
        this.$confirm(this.$t("message.areyousure"), this.$t("message.ok"), {
          confirmButtonText: this.$t("message.ok"),
          cancelButtonText: this.$t("message.cancel"),
          type: "warning"
        }).then(() => {
          this.doSendCmd("factoryReset");
        });
      } else if (command == "exportlog") {
        api.onRequest("$method.exportDebugLog.sys.cmd").then((msg) => {
          var res = JSON.parse(msg);
            if (res && res.code == 0) {
              var url = "http://" + getHostName() + ":8080/_default/" + res.data.url.substring(15);
              var fileName = res.data.url.split("/")[res.data.url.split("/").length - 1];
              downloadFile(url, fileName)              
            } else{
              this.showCodeMsg(res.code, this, res.msg);
            }
        });
      } else if (command == "tool") {
        window.open("stbpc.html");
      }
    },
    onSubmit() {
      if (
        !this.authInfo.username ||
        !this.authInfo.oldpassword ||
        !this.authInfo.newpassword ||
        this.authInfo.newpassword != this.authInfo.confirmpassword
      ) {
        return;
      }
      var option = {
        username: this.authInfo.username,
        password: "md5#" + md5(this.authInfo.oldpassword),
        newPassword: "md5#" + md5(this.authInfo.newpassword)
      };
      api.onRequest(
        "$method.changePassword.auth.cmd",
        JSON.stringify(option),
        null,
        null,
        function(msg, reply) {
          var res = JSON.parse(msg);
          if (res && res.code == 0) {
            this.notification("Success", "");
            this.$router.push("/login");
          } else {
            this.showCodeMsg(res.code, this, res.msg);
          }
        }.bind(this)
      );
    },
    doSendCmd(cmd) {
      api.onRequest(
        "$method." + cmd + ".sys.cmd",
        null,
        null,
        null,
        function(msg, reply) {
          var res = JSON.parse(msg);
          if (res && res.code == 0) {            
            if(cmd == 'factoryReset'){
              this.notification("Success", this.$t('message.cmd.factoryCompleted'));    
              var timer = setTimeout(() => {
                this.$router.push("/login");
                clearTimeout(timer)
              }, 2000);                        
            } else{                            
              this.notification("Success", this.$t('message.willbeRestart'));
               var timer = setTimeout(() => {
                this.$router.push("/login");
                clearTimeout(timer)
              }, 3500); 
            }
          } else {
            this.notification("error", msg);
          }
        }.bind(this)
      );
    },
    getCustomInfo(lang){
      var xhr = new XMLHttpRequest();
      xhr.open("GET", "http://" + getHostName() + ":8080/custom/info.json");
      xhr.onload = function(res) {
      };
      xhr.onerror = function(err) {
        console.log("onerror:", err);
      };
      xhr.onreadystatechange = function() {
        if (xhr.readyState == 4) {
          //判断http的交互是否成功
          if (xhr.status == 200) {
            var responseText = xhr.responseText;
            var res = JSON.parse(responseText);
            this.$store.dispatch("system/getCompanyInfo", res);
            console.log("this.$i18n:", this.$i18n);
          }
        }
      }.bind(this);
      xhr.send(null); 
    },
    getServerI18nlocales(lang){
      var url = '';
      url = "http://" + getHostName() + ":8080/locales/" + lang + "/res.json"
      var xhr = new XMLHttpRequest();
      xhr.open("GET", url);
      xhr.onload = function(res) {
        
      };
      xhr.onerror = function(err) {
        console.log("onerror:", err);
      };
      xhr.onreadystatechange = function() {
        if (xhr.readyState == 4) {
          //判断http的交互是否成功
          if (xhr.status == 200) {
            var responseText = xhr.responseText;
            var res = {}
            try {
              res = JSON.parse(responseText);
              if(lang == 'zh-cn'){
                zh.message.code = res.code
                zh.message.method = res.method
                this.$i18n.setLocaleMessage('zh-cn',  zh);   
              }else if(lang == 'en'){
                en.message.code = res.code
                en.message.method = res.method
                this.$i18n.setLocaleMessage('en',  en); 
              }
            }
            catch (e) {
              console.warn('Json Parse Error:', e);
            }
          }
        }
      }.bind(this);
      xhr.send(null);   
    },
    onReboot(){
      api.onRequest("$method.reboot.sys.cmd", null, null, null, function(msg, reply) {
          var res = JSON.parse(msg);
          if (res && res.code == 0) {
            // this.$router.push("/login");
            this.showRebootWait();
            this.notification("Success", "");
          } else {
            this.notification("error", msg);
          }
        }.bind(this)
      );
    },
    showRebootWait(){
      this.loading = true;
      this.fullscreenLoading = true;
      var timeout = setTimeout(() => {
        var interval = setInterval(()=>{
          var ws = new WebSocket("ws://" + getHostName() + ":8080/_ws/stbp");
            ws.onopen = function() {
              window.location.href = "http://" + getHostName() + ":8080";
              this.loading = true;
              this.fullscreenLoading = true;
              clearInterval(interval);
              clearTimeout(timeout);
            };
        }, 3 * 1000)
      }, 5000);
    }
  }
};
</script>

<style>
@import url("../../../assets/icon/iconfont.css");
.el-header,
.el-footer {
  background-color: #eff2f7;
  color: #000;
  text-align: left;
  line-height: 100%;
}

.el-aside {
  background-color: #324057;
  color: #bfcbd9;
  text-align: center;
  min-width: 291px;
  /* line-height: 200px; */
}

.el-main {
  background-color: #ffffff;
  color: #333;
  text-align: center;
  line-height: 100%;
  padding: 0px;
  font-size: 16px;
}
body > .el-container {
  margin-bottom: 0px;
}
.el-container,
.tac,
.col24,
.el-aside {
  height: 100%;
  color: #bfcbd9;
}
.avator {
  width: 46px;
  height: 46px;
}
.menu i {
  width: 20px;
  height: 20px;
  margin-left: 14px;
}
.menu span {
  font-size: 18px;
  margin-left: 20px;
}
.dropdown {
  margin-top: 7px;
}
.product {
  height: 69px;
  font-size: 18px;
}
.sidefoot {
  color: #bfcbd9;
  bottom: 0;
  position: absolute;
  text-align: left;
  font-size: 14px;
}
.no-redirect {
  color: #97a8be;
  cursor: text;
  margin-left: -1px;
}
.menu span[data-v-34feeb6e] {
  font-size: 18px;
  margin-left: 20px;
}
.el-menu {
  border-right: 0;
}
.el-menu a {
  display: block;
}

a {
  color: #324057;
  text-decoration: none;
}
.el-menu-item.is-active i {
  color: inherit;
}
.el-menu-item i {
  position: absolute;
  margin-top: 16px;
  right: 20%;
}
.menu span {
  position: absolute;
  font-size: 18px;
  left: 20%;
  /* left: 5.5%; */
}
/* a:link {
  color: #97a8be;
  text-decoration: none;
} */
</style>
